<template>
  <div class="app-container">
    <div class="bannerContent">
      <div
        v-for="(item,index) in bannerList"
        :key="index"
        :ref="'box'+index"
        class="upload-contanier"
        draggable="true"
        @dragstart="dragstart($event,index)"
        @dragend="dragend($event,item)"
        @dragover.prevent="dragover($event,index)"
        @drop="Drop($event, item)"
      >
        <el-form :model="item" label-width="auto">
          <el-form-item :label="`banner${index + 1} 名称：`" prop="name">
            <el-input v-model="item.name" placeholder="请输入 Banner 名称" />
          </el-form-item>
          <!-- <el-form-item :label="`banner${index + 1} 图片（PC）：`" prop="image">
            <k-upload-file
              ref="upload1"
              v-model="item.url"
              upload-style="img"
              @successUpload="successUpload($event,index,1)"
            />
            <span style="color: #b2b2b2;cursor: pointer;" @click="onclickview(item.url)">只能上传jpg/png文件，且不超过2M</span>
          </el-form-item>
          <el-form-item :label="`banner${index + 1} 跳转链接（PC）：`" prop="linkurl">
            <el-input v-model="item.redirectUrl" placeholder="请输入跳转链接：" />
          </el-form-item> -->
          <el-form-item :label="`banner${index + 1} 图片（手机）：`" prop="image">
            <k-upload-file
              ref="upload1"
              v-model="item.mobileUrl"
              upload-style="img"
              @successUpload="successUpload($event,index,2)"
            />
            <span style="color: #b2b2b2;cursor: pointer;" @click="onclickview(item.mobileUrl)">只能上传jpg/png文件，且不超过2M</span>
          </el-form-item>
          <el-form-item :label="`banner${index + 1} 跳转链接（手机）：`" prop="linkurl">
            <el-input v-model="item.mobileRedirectUrl" placeholder="请输入跳转链接：" />
          </el-form-item>
          <el-form-item label="显示状态：" prop="status">
            <el-switch
              v-model="item.status"
              active-color="#3b425d"
                inactive-color="#E9EBF2"
              :active-value="1"
              :inactive-value="0"
              @change="updatebannerStatus($event,index + 1)"
            />
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="footer">
      <button class="btnStyle" @click="saveBanner">保存</button>
    </div>
    <el-image
      ref="previewImg"
      style="width: 0px; height: 0px"
      :preview-src-list="previewSrcList"
    />
  </div>
</template>

<script>
import { bannerListData, saveBanner } from '@/api/message/message'

export default {
  components: {},
  data() {
    return {
      bannerList: [
        { id: undefined, name: '', url: '', mobileUrl: '', redirectUrl: '', mobileRedirectUrl: '', status: 0, sort: 1 },
        { id: undefined, name: '', url: '', mobileUrl: '', redirectUrl: '', mobileRedirectUrl: '', status: 0, sort: 2 },
        { id: undefined, name: '', url: '', mobileUrl: '', redirectUrl: '', mobileRedirectUrl: '', status: 0, sort: 3 },
        { id: undefined, name: '', url: '', mobileUrl: '', redirectUrl: '', mobileRedirectUrl: '', status: 0, sort: 4 },
        { id: undefined, name: '', url: '', mobileUrl: '', redirectUrl: '', mobileRedirectUrl: '', status: 0, sort: 5 },
        { id: undefined, name: '', url: '', mobileUrl: '', redirectUrl: '', mobileRedirectUrl: '', status: 0, sort: 6 },
        { id: undefined, name: '', url: '', mobileUrl: '', redirectUrl: '', mobileRedirectUrl: '', status: 0, sort: 7 },
        { id: undefined, name: '', url: '', mobileUrl: '', redirectUrl: '', mobileRedirectUrl: '', status: 0, sort: 8 }
      ],
      previewSrcList: [],
      dragging: null, // 当前拖拽的元素
      dragstartIndex: 0, // 拖拽开始索引
      dragendIndex: 0 // 拖拽结束索引
    }
  },
  created() {
    this.bannerListData()
  },
  mounted() {
    console.log('123', this.$refs.previewImg.previewSrcList)
  },
  methods: {
    // 开始拖拽
    dragstart(index, itemBox) {
      this.dragstartIndex = itemBox
      this.dragging = this.bannerList[itemBox]
    },
    // 拖拽中
    dragover(e, itemBox) {
      e.dataTransfer.dropEffect = 'move'
      this.dragendIndex = itemBox
      for (let i = 0; i < this.bannerList.length; i++) {
        if (i === itemBox) this.$refs['box' + i][0].style.border = '1px dashed blue'
        if (i !== itemBox) this.$refs['box' + i][0].style.border = '1px dashed #d9d9d9'
      }
      this.$refs['box' + this.dragstartIndex][0].style.border = '1px dashed red'
      this.$refs['box' + this.dragstartIndex][0].style.offsetLeft = e.clientX
    },
    // 当放置被拖元素时
    Drop(e, item) {
      e.dataTransfer.dropEffect = 'move'
      if (item === this.dragging) {
        return
      }
      const newItems = [...this.bannerList]
      const from = newItems.indexOf(this.dragging)
      const to = newItems.indexOf(item)
      newItems[from] = item
      newItems[to] = this.dragging
      this.bannerList = newItems
    },
    // 拖拽结束
    dragend(index, itemBox) {
      this.$refs['box' + this.dragstartIndex][0].style.border = '1px dashed #d9d9d9'
      this.$refs['box' + this.dragendIndex][0].style.border = '1px dashed #d9d9d9'
      this.dragging = null
    },
    onclickview(img) {
      this.previewSrcList = [img]
      this.$refs.previewImg.showViewer = true
    },
    // 获取banner信息
    bannerListData() {
      bannerListData().then(res => {
        const originList = res.data.data
        if (originList.length === 0) return
        this.bannerList = res.data.data
        this.addPath(this.bannerList, 1)
      })
    },
    // 图片添加删除连接
    addPath(v, index) {
      if (index == 1) {
        v.map((item, index) => {
          console.log(item.mobileUrl.indexOf(this.$store.state.user.imagePath), '/1')
          if (item.url && item.url.indexOf(this.$store.state.user.imagePath) == -1) item.url =  item.url
          if (item.mobileUrl && item.mobileUrl.indexOf(this.$store.state.user.imagePath) == -1) item.mobileUrl =  item.mobileUrl
          return item
        })
      }
    },
    replaceString(A) {
      return A.replace(new RegExp(this.$store.state.user.imagePath, 'g'), '')
    },
    saveBanner(e) {
      const target = e.target
      const arr = JSON.parse(JSON.stringify(this.bannerList))
      arr.map((item, index) => {
        item.sort = index + 1
        if (item.url.indexOf(this.$store.state.user.imagePath) == 0) item.url = this.replaceString(item.url)
        if (item.mobileUrl.indexOf(this.$store.state.user.imagePath) == 0) item.mobileUrl = this.replaceString(item.mobileUrl)
      })
      saveBanner(arr).then(res => {
        if (res.data.success) {
          this.$message.success('保存成功')
          this.bannerListData()
        } else {
          this.$message.success(res.data.msg)
        }
      })
      target.blur()
    },

    // 单独开关无效 整体保存有效
    updatebannerStatus(value, index) {
      // updatebannerStatus({ 'bannerId': 1, 'status': 0 }).then(res => {
      //   this.$log(res)
      //   if (res.data.success) {
      //     this.$message.success('更新成功')
      //   } else {
      //     this.$message.success(res.data.msg)
      //   }
      // })
    },
    successUpload(data, index, flag) {
      if (flag === 1) {
        this.bannerList[index].url = data
      } else {
        this.bannerList[index].mobileUrl = data
      }
      this.addPath(this.bannerList, 1)
    }
  }
}
</script>
<style lang="scss" scoped>
$mainColor:#36B58B;// 主色调
.item {
	display: inline-block;
	margin-left: 20px;
	margin-bottom: 20px;
	width: 200px;
	height: 200px;
	border-radius: 4px;
	box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
}
.bannerContent{
  // width: 50%;
  display: flex;
  flex-wrap: wrap;
}
.upload-contanier {
  width: 48%;
  margin: 20px;
  height: 750px;
  border: 1px dashed #d9d9d9;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  .el-form-item {
    margin-bottom: 12px;
  }
  ::v-deep .el-input__inner:focus {
    border-color: $mainColor;
  }
}
.submitBtn1 {
    display: inline-block;
    cursor: pointer;
  }

.footer {
  text-align: center;
  margin-top: 20px;
}

 ::v-deep .avatar-uploader{
 &-icon {
      font-size: 28px;
      color: #8c939d;
      width: 280px;
      height: 150px;
      line-height: 150px;
      text-align: center;
    }
   .avatar {
      width: 280px;
      height: 150px;
      display: block;
    }
 }
</style>
